package com.bw.baserecyclerview.diff;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListUpdateCallback;
import androidx.recyclerview.widget.RecyclerView;

import com.bw.baserecyclerview.R;

import java.util.ArrayList;
import java.util.List;

public class DiffActivity extends AppCompatActivity {

    private List<DiffEntity>sourceList = new ArrayList<>();
    private List<DiffEntity>list = new ArrayList<>();
    private RecyclerView recyclerView;
    private DiffAcapter adapter;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diff);
        initData();
        adapter = new DiffAcapter(sourceList);
        recyclerView = findViewById(R.id.diff_rv);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        findViewById(R.id.diff_update_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //模拟下拉刷新数据改变
                DiffEntity entity = new DiffEntity(0,"施源");
                list.set(0,entity);
                DiffUtil.DiffResult result = DiffUtil.calculateDiff(new DiffAdapterCallBack(sourceList,list));
                result.dispatchUpdatesTo(new ListUpdateCallback() {
                    @Override
                    public void onInserted(int position, int count) {

                    }

                    @Override
                    public void onRemoved(int position, int count) {

                    }

                    @Override
                    public void onMoved(int fromPosition, int toPosition) {

                    }

                    @Override
                    public void onChanged(int position, int count, @Nullable Object payload) {
                        DiffEntity entity1 = (DiffEntity) payload;
                        adapter.getList().set(position,entity1);
                        adapter.notifyItemChanged(position,count);
                    }
                });
            }
        });
    }

    private void initData(){
        for (int i = 0;i < 50;i ++){
            sourceList.add(new DiffEntity(i,"sourceList:"+i));
            list.add(new DiffEntity(i,"sourceList:"+i));
        }
    }

}
